package cn.zyl.demo.common.tools;

import java.util.Arrays;

/**
 * CardTool类说明:证件号工具类
 *
 * @author wsz
 * @version v1.0
 * @date 2020-07-22
 */
public class CardTool {
    private CardTool(){throw new IllegalAccessError("CardTool");}
    /** 身份证号-最短位数*/
    private final static int ID_CARD_MIN_LENGTH = 8;
    /** 手机号-最短位数*/
    private final static int PHONE_MIN_LENGTH = 7;
    /** 符号* */
    private final static char STAR = '*';
    /** 手机号-脱敏是用的正则*/
    private final static String DESENSITIZATION_PHONE_REGEX = "(\\w{3})(\\w+)(\\w{4})";
    /** 身份证-脱敏是用的正则*/
    private final static String DESENSITIZATION_ID_CARD_REGEX = "(\\w{4})(\\w+)(\\w{4})";
    private final static String DESENSITIZATION_START_SEAT = "$1";
    private final static String DESENSITIZATION_END_SEAT = "$3";
    /**
     * 身份证号脱敏，默认前4位后4位明文
     *
     * @param idCard 身份证号
     * @return 为空/长度小于15，返回原值
     */
    public static String desensitizationIdCard(String idCard) {
        //为空；长度小于15
        if (StringTool.isBlank(idCard) || idCard.length() < ID_CARD_MIN_LENGTH) { return idCard; }
        int len = idCard.length() - ID_CARD_MIN_LENGTH;
        return desensitization(idCard, len, DESENSITIZATION_ID_CARD_REGEX);
    }
    /**
     * 电话号脱敏，默认前3位后4位明文
     *
     * @param phone 电话号
     * @return 为空/长度小于7，返回原值
     */
    public static String desensitizationPhone(String phone) {
        //为空；长度小于15
        if (StringTool.isBlank(phone) || phone.length() < PHONE_MIN_LENGTH) { return phone; }
        int len = phone.length() - PHONE_MIN_LENGTH;
        return desensitization(phone, len, DESENSITIZATION_PHONE_REGEX);
    }

    /**
     * 内容脱敏
     * @param str 需要脱敏的内容
     * @param starSize 脱敏符号*长度
     * @param regex 脱敏正则
     * @return 已脱敏的内容
     */
    public static String desensitizationStr(String str,int starSize,final String regex){
        return desensitization(str, starSize, regex);
    }
    /**
     * 内容脱敏
     * @param str 需要脱敏的内容
     * @param starSize 脱敏符号*长度
     * @param regex 脱敏正则
     * @return 已脱敏的内容
     */
    private static String desensitization(String str,int starSize,final String regex){
        char[] c = new char[starSize];
        Arrays.fill(c, 0, starSize, STAR);
        String replacement = DESENSITIZATION_START_SEAT + new String(c) + DESENSITIZATION_END_SEAT;
        return str.replaceAll(regex, replacement);
    }
    private static void idCardEnd(String idCard){
        /*18位身份证号规则
        * 1-2：所在省（直辖市、自治区）的代码
        * 3-4：所在地级市（自治州）的代码
        * 5-6：所在区（县、自治县、县级市）的代码
        * 7-14：出生年月日
        * 15-16：所在地的派出所的代码
        * 17：性别，奇数 男；偶数 女
        * 18：校验码，0-9 X，[1,0,X,9,8,7,6,5,4,3,2]
        * https://www.jianshu.com/p/ead5b08e9839
        * https://jingyan.baidu.com/article/72ee561abd962fe16038df48.html
        * */
    }
    public static void main(String[] args) {
        System.out.println(desensitizationIdCard("110229190001012484"));
        System.out.println(desensitizationPhone("13733333731"));
    }
}
